package com.xdjd.mobile.business.service;

import com.alibaba.fastjson.JSON;
import com.gitee.easyopen.ApiContext;
import com.gitee.easyopen.exception.ApiException;
import com.gitee.easyopen.util.RequestUtil;
import com.xdjd.mobile.business.entity.param.wxpay.WXPay;
import com.xdjd.mobile.business.entity.param.wxpay.WxPayUnifiedOrderParam;
import com.xdjd.mobile.business.entity.result.wxpay.WxPayUnifiedOrderResult;
import com.xdjd.mobile.system.config.WxpayExtConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Service
public class WxpayService implements EnvironmentAware {

    private static final Logger logger = LoggerFactory.getLogger(WxpayService.class);

    @Autowired
    private WxpayExtConfig wxpayConfig;

    private volatile WXPay client;

    private String springActiveProfile;

    @Override
    public void setEnvironment(Environment environment) {
        springActiveProfile = environment.getProperty("spring.profiles.active");
    }

    public WxPayUnifiedOrderResult createUnifiedOrder(WxPayUnifiedOrderParam param) throws UnsupportedEncodingException {
        WxPayUnifiedOrderResult result = new WxPayUnifiedOrderResult();
        result.setNeedPay(1);
        //每次生成 订单号 + 随机数 作为支付单号 防止因为价格修改导致的 201商户订单号重复
        Map<String, String> data = new HashMap<>();
        data.put("body", "");
        data.put("out_trade_no", param.getOutTradeNo());
        data.put("fee_type", "CNY");
        if (springActiveProfile != null && "dev,test".contains(springActiveProfile)) {
            data.put("total_fee", "1");
        } else {
            data.put("total_fee", param.getPayAmount().toString());
        }
        data.put("spbill_create_ip", RequestUtil.getClientIP(ApiContext.getRequest()));
        data.put("notify_url", wxpayConfig.getNotifyUrl());
        // JSAPI 公众号支付 NATIVE 扫码支付 APP APP支付
        data.put("trade_type", "APP");
        try {
            logger.info("统一下单参数===:" + JSON.toJSONString(data));
            Map<String, String> resp = getPayClient().unifiedOrder(data);
            logger.info("统一下单接口返回:" + JSON.toJSON(resp));
            //通信成功判断
            if (null != resp.get("return_code") && resp.get("return_code").equalsIgnoreCase("SUCCESS")) {
                //交易成功判断
                if (null != resp.get("result_code") && resp.get("result_code").equalsIgnoreCase("SUCCESS")) {
                    result.setErrMsg("统一下单成功");
                    result.setPrepayId(resp.get("prepay_id"));
                } else {
                    String err_code_des = "系统异常，请用相同参数重新调用";
                    if (null != resp.get("err_code_des")) {
                        err_code_des = resp.get("err_code_des");
                    }
                    result.setErrMsg(err_code_des);
                }
            } else {
                String return_msg = "签名失败";
                if (null != resp.get("return_msg")) {
                    return_msg = resp.get("return_msg").toString();
                }
                result.setErrMsg(return_msg);
            }
        } catch (Exception e) {
            logger.error("统一下单接口报错", e);
            throw new ApiException("统一下单接口报错" + e);
        }
        return result;
    }

    private WXPay getPayClient() throws Exception {
        if (client == null) {
            synchronized (WxpayService.class) {
                if (client == null) {
                    try {
                        if (StringUtils.isEmpty(wxpayConfig.getAppID())) {
                            throw new ApiException("appID不能为空");
                        }
                        if (StringUtils.isEmpty(wxpayConfig.getMchID())) {
                            throw new ApiException("mchID不能为空");
                        }
                        if (StringUtils.isEmpty(wxpayConfig.getKey())) {
                            throw new ApiException("appKey不能为空");
                        }
                        if (StringUtils.isEmpty(wxpayConfig.getAppSecret())) {
                            throw new ApiException("secret不能为空");
                        }
                        if (StringUtils.isEmpty(wxpayConfig.getNotifyUrl())) {
                            throw new ApiException("notifyUrl不能为空");
                        }
                        client = new WXPay(wxpayConfig);
                    } catch (Exception e) {
                        logger.error("创建微信支付请求错误", e);
                        throw e;
                    }
                }
            }
        }
        return client;
    }
}
